package com.example.h5server.controller;

import com.example.h5server.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
@Tag(name = "文件上传接口", description = "提供图片上传相关接口")
public class FileUploadController {
    @Value("${file.upload-image-path}")
    private String uploadImagePath;
    @Value("${file.upload-pdf-path}")
    private String uploadPDFPath;

    @PostMapping("/image")
    @Operation(summary = "上传图片", description = "上传单个图片文件")
    public Result<String> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return Result.error(400, "图片文件不能为空");
            }

            // 验证文件类型
            if (!isImageFile(file)) {
                return Result.error(400, "只支持图片格式文件(jpg, jpeg, png, gif)");
            }

            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.isEmpty()) {
                return Result.error(400, "文件名不能为空");
            }

            // 生成唯一文件名
            String fileExtension = getFileExtension(originalFilename);
            String uniqueFileName = System.currentTimeMillis() + "_" +
                    UUID.randomUUID().toString().substring(0, 8) +
                    fileExtension;

            // 创建上传目录
            Path uploadDir = Paths.get(uploadImagePath);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }

            // 保存文件
            Path filePath = uploadDir.resolve(uniqueFileName);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 返回访问URL
            String fileUrl = "/uploadsImg/" + uniqueFileName;
            return Result.success("图片上传成功", fileUrl);

        } catch (IOException e) {
            return Result.error(500, "图片上传失败: " + e.getMessage());
        } catch (Exception e) {
            return Result.error(500, "系统错误: " + e.getMessage());
        }
    }
    @PostMapping("/pdf")
    @Operation(summary = "上传PDF文件", description = "上传单个PDF文件")
    public Result<String> uploadPdf(@RequestParam("file") MultipartFile file) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return Result.error(400, "PDF文件不能为空");
            }
            // 检查文件大小（例如限制为50MB）
            long maxSize = 50 * 1024 * 1024; // 50MB
            if (file.getSize() > maxSize) {
                return Result.error(400, "PDF文件大小不能超过50MB");
            }
            // 验证文件类型
            if (!isPdfFile(file)) {
                return Result.error(400, "只支持PDF格式文件");
            }

            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.isEmpty()) {
                return Result.error(400, "文件名不能为空");
            }

            // 生成唯一文件名
            String fileExtension = getFileExtension(originalFilename);
            String baseName = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            String timestamp = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String uniqueFileName = baseName + "_" + timestamp + "_" +
                    UUID.randomUUID().toString().substring(0, 8) +
                    fileExtension;
            // 创建上传目录
            Path uploadDir = Paths.get(uploadPDFPath);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }

            // 保存文件
            Path filePath = uploadDir.resolve(uniqueFileName);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 返回访问URL
            String fileUrl = "/uploadsPDF/" + uniqueFileName;
            return Result.success("PDF文件上传成功", fileUrl);

        } catch (IOException e) {
            return Result.error(500, "PDF文件上传失败: " + e.getMessage());
        } catch (Exception e) {
            return Result.error(500, "系统错误: " + e.getMessage());
        }
    }

    /**
     * 验证是否为PDF文件
     */
    private boolean isPdfFile(MultipartFile file) {
        String contentType = file.getContentType();
        if (contentType == null) {
            return false;
        }
        return "application/pdf".equals(contentType);
    }


    /**
     * 验证是否为图片文件
     */
    private boolean isImageFile(MultipartFile file) {
        String contentType = file.getContentType();
        if (contentType == null) {
            return false;
        }
        return contentType.startsWith("image/");
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String filename) {
        if (filename.contains(".")) {
            return filename.substring(filename.lastIndexOf("."));
        }
        return "";
    }




}
